package com.onesports.intelligent.k12.polarlight.common.domain.comm.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: xiong pengfei
 * @date: 2021-11-26
 * @description:
 */
public class DataTreeUtil {

    /**
     * 构造无根树形结构数据，比如系统左侧菜单栏
     *
     * @param paramList
     * @param rootNodeId
     * @param <ID>
     * @param <T>
     * @return
     */
    public static <ID, T extends DataTree<T, ID>> List<T>
    buildTreeWithoutRoot(List<T> paramList, ID rootNodeId) {
        //从2级节点开始构造
        List<T> returnList = paramList.stream().filter(e -> e.getParentId().equals(rootNodeId)).collect(Collectors.toList());
        for (T parentObj : returnList) {
            toTreeChildren(parentObj, paramList);
        }
        return returnList;
    }

    public static <ID, T extends DataTree<T, ID>> List<T> buildTree(List<T> paramList, ID rootNodeId) {
        List<T> returnList = paramList.stream().filter(e -> e.getId().equals(rootNodeId)).collect(Collectors.toList());
        for (T parentObj : returnList) {
            toTreeChildren(parentObj, paramList);
        }
        return returnList;
    }

    private static <ID, T extends DataTree<T, ID>> void toTreeChildren(T parentObj, List<T> paramList) {
        paramList.forEach(e -> {
            if (e.getParentId().equals(parentObj.getId())) {
                if (parentObj.getChildren() == null) {
                    parentObj.setChildren(new ArrayList<T>());
                }
                parentObj.getChildren().add(e);
            }
        });
        if (parentObj.getChildren() != null) {
            parentObj.getChildren().forEach(e -> {
                toTreeChildren(e, paramList);
            });
        }
    }
}
